"""
@File    :   app.py
@Time    :   2024/01/22 17:51:06
@Author  :   glx 
@Version :   1.0
@Contact :   18095542g@connect.polyu.hk
@Desc    :   motion recognition 
"""

# here put the import lib

import os
import json
from flask import Flask, request, abort, jsonify, Response
from werkzeug.wrappers import response
import datetime
from copy import deepcopy
from src.main import main

app = Flask(__name__)


@app.errorhandler(Exception)
def handle_custom_exception(error):
    response = jsonify({"message": str(error)})
    return response, 500


@app.route("/motion_rec/", methods=["GET", "POST"])
def motion_rec(if_debug=True):
    if request.method == "GET":
        return "use POST method"
    if request.method == "POST":
        try:
            try:
                input_data = request.get_json(force=True)
            except Exception as e:
                # 返回400
                response = Response("错误的输入，无法解析为json格式")
                response.status_code = 400
                abort(response)

            # 关键字缺失检测
            if if_debug:
                date = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
                ip = request.remote_addr
                os.makedirs(f"logger/{ip}", exist_ok=True)
                os.makedirs(f"logger/{ip}/{date}", exist_ok=True)

                with open(os.path.join(f"logger/{ip}/{date}", "input.json"), "w") as f:
                    json.dump(input_data, f, indent=4)

            # 规划
            result = main(input_data)
            # debug
            if if_debug:
                prase_result = deepcopy(result)
                with open(
                    os.path.join(f"logger/{ip}/{date}", "output.json"),
                    "w",
                    encoding="utf-8",
                ) as f:
                    json.dump(prase_result, f, indent=4, ensure_ascii=False)
                # print(date)
                # prased_output = prase_output(prase_result)
                # with open(
                #     os.path.join(f"logger/{ip}/{date}", "prased_output.json"),
                #     "w",
                #     encoding="utf-8",
                # ) as f:
                #     json.dump(
                #         prase_result,
                #         f,
                #         indent=4,
                #         ensure_ascii=False,
                #     )

            return jsonify(result)
        except Exception as e:
            print(e)
            raise e


if __name__ == "__main__":
    app.run("0.0.0.0", 5000)

    # 部署到服务器上
    # server = pywsgi.WSGIServer(('127.0.0.1', 5000), app)
    # server.serve_forever()
